package com.atguigu.edu.controller;


import com.atguigu.common.util.R;
import com.atguigu.edu.entity.EduCourse;
import com.atguigu.edu.entity.EduVideo;
import com.atguigu.edu.entity.vo.EduCourseVo;
import com.atguigu.edu.entity.vo.EduCoursePublishVo;
import com.atguigu.edu.entity.vo.query.EduCourseQuery;
import com.atguigu.edu.service.EduChapterService;
import com.atguigu.edu.service.EduCourseService;
import com.atguigu.edu.service.EduVideoService;
import com.atguigu.edu.service.client.VodClient;
import com.atguigu.edu.util.PUBLISH_STATUS;
import com.atguigu.service.base.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author alexzshl
 * @since 2021-05-04
 */
@RestController
@RequestMapping("/api/edu/course")
@Api("课程")
@CrossOrigin
public class EduCourseController {

    @Autowired
    private EduCourseService eduCourseService;

    @Resource
    private EduChapterService eduChapterService;

    @Resource
    private EduVideoService eduVideoService;

    @Resource
    private VodClient vodClient;

    @GetMapping(value = {"/list", "list"})
    @ApiOperation("获取所有课程")
    public R getAll() {
        List<EduCourse> data = eduCourseService.list(null);
        return R.ok()
                .data("total", data.size())
                .data("items", data)
                .data("data", data);
    }

    @PostMapping("/page/{current}/{limit}")
    @ApiOperation("查询课程-条件分页查询")
    public R page(
            @ApiParam(name = "current", value = "当前页", required = true)
            @PathVariable("current") Integer current,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable("limit") Integer limit,
            @ApiParam(name = "query", value = "课程查询条件", required = false)
            @RequestBody(required = false) EduCourseQuery query) {
        Page<EduCourse> page = new Page<>(current, limit);
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<EduCourse>();

        wrapper
                .like(!StringUtils.isEmpty(query.getTitle()), "title", query.getTitle())
                .eq(!StringUtils.isEmpty(query.getStatus()), "status", query.getStatus())
                .ge(!StringUtils.isEmpty(query.getBegin()), "gmt_create", query.getBegin())
                .le(!StringUtils.isEmpty(query.getEnd()), "gmt_create", query.getEnd())
                .orderByDesc("gmt_create");

        eduCourseService.page(page, wrapper);

        long total = page.getTotal();
        List<EduCourse> records = page.getRecords();
        return R.ok()
                .data("total", total)
                .data("data", records)
                .data("items", records);
    }

    @PostMapping("/delete/{courseId}")
    @ApiOperation("根据 id 删除课程（逻辑删除）- 返回统一数据格式")
    public R removeCourseById(
            @ApiParam(name = "courseId", value = "课程id", required = true)
            @PathVariable(name = "courseId") String courseId) {
        HashMap<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("course_id", courseId);

        // 删除课程下所有课时
        // eduVideoService.remove(new QueryWrapper<EduVideo>().eq("course_id", courseId));

        // 提取所有视频id
        List<String> videoSourceIds = eduVideoService.list(new QueryWrapper<EduVideo>()
                .select("video_source_id")
                .eq("course_id", courseId))
                .stream()
                .map(eduVideo -> eduVideo.getVideoSourceId())
                .filter(videoSourceId -> !StringUtils.isEmpty(videoSourceId))
                .collect(Collectors.toList());
        if (videoSourceIds.size() > 0) {
            vodClient.deleteBatch(videoSourceIds);
        }

        if (!eduVideoService.removeByMap(deleteMap)) {
            throw new GuliException(20001, "删除课时失败");
        }

        // 删除课程下所有章节
        if (!eduChapterService.removeByMap(deleteMap)) {
            throw new GuliException(20001, "删除章节失败");
        }

        // 删除课程
        if (!eduCourseService.removeById(courseId)) {
            throw new GuliException(20001, "删除课程失败");
        }
        return R.ok();
    }



    @PostMapping("/addCourseInfo")
    @ApiOperation("新建课程（课程基础信息）")
    public R addCourseInfo(@RequestBody EduCourseVo courseInfo) {
        EduCourseVo courseInfoT = eduCourseService.saveCourseInfo(courseInfo);
        return R.ok().data("courseId", courseInfo.getId()).data("courseInfo", courseInfoT);
    }

    @GetMapping("/getCourseInfo/{courseId}")
    @ApiOperation("获取课程信息")
    public R getCourseInfo(@PathVariable("courseId") String courseId) {
        EduCourseVo courseInfo = eduCourseService.getCourseInfo(courseId);
        return R.ok().data("data", courseInfo);
    }

    @PostMapping("/updateCourseInfo")
    @ApiOperation("更新课程信息")
    public R updateCourseInfo(@RequestBody EduCourseVo courseInfo) {
        Boolean update = eduCourseService.updateCourseInfo(courseInfo);
        return R.ok().message("更新课程信息成功");
    }



    /**
     * publish - 获取课程信息
     * @param courseId
     * @return
     */
    @GetMapping("/prepublish/{courseId}")
    @ApiOperation("获取课程信息（预发布）")
    public R getCoursePublishInfo(@PathVariable("courseId") String courseId) {
        EduCoursePublishVo data = eduCourseService.getEduCoursePublishVoById(courseId);
        return R.ok()
                .data("data", data)
                .data("publishCourse", data)
                .data("prePublishCourseInfo", data);
    }

    @PostMapping("/publish/{courseId}")
    @ApiOperation("发布课程（修改课程状态信息）")
    public R publishCourse(@PathVariable("courseId") String courseId) {
        // EduCourse course = eduCourseService.getById(courseId);
        EduCourse course = new EduCourse();
        course.setId(courseId).setStatus(PUBLISH_STATUS.NORMAL);
        eduCourseService.updateById(course);
        return R.ok().message("发布成功");
    }

    @PostMapping("/dePublish/{courseId}")
    @ApiOperation("发布课程（修改课程状态信息）")
    public R dePublishCourse(@PathVariable("courseId") String courseId) {
        // EduCourse course = eduCourseService.getById(courseId);
        EduCourse course = new EduCourse();
        course.setId(courseId).setStatus(PUBLISH_STATUS.DRAFT);
        eduCourseService.updateById(course);
        return R.ok().message("取消发布成功");
    }


    /**
     * 服务熔断降级测试
     */
    @GetMapping("/test01")
    public R test01(String param) {
        R result = vodClient.testHystrix("test hystrix");
        if (result.getCode() == 20000) {
            return R.ok();
        } else {
            return R.error();
        }
    }
}

